﻿using HRIS.Browser.UI.ConfigReader;
using Iit.Automation.Browsers.Shared;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HRIS.Browser.UI.Framework.DesktopWebControls
{
    public class Menu : MenuBase<RemoteWebElement>
    {
        private IBrowser _browser;
        private By _selector;
        private TimeSpan _timeout;

        public void Click()
        {
            if (!(Element != null && Element.Displayed && Element.Enabled))
            {
                ConfigureMenu();
            }

            Element.Click();
        }

        private void ConfigureMenu()
        {
            WebDriverWait wait = new WebDriverWait(_browser, _timeout);
            Element = wait.Until<RemoteWebElement>((b) =>
               {
                   try
                   {
                       return (RemoteWebElement)b.FindElement(_selector);
                   }
                   catch (Exception)
                   {
                       return null;
                   }
               });
        }

        public Menu()
        { }

        public Menu(HRISEnums.MenuItems item, IBrowser browser, By selector, TimeSpan? selectionTimeout = null)
        {
            _browser = browser;
            _selector = selector;
            _timeout = selectionTimeout.HasValue ? selectionTimeout.Value : TimeSpan.FromSeconds(2);
            MenuItem = item;

            try
            {
                ConfigureMenu();
            }
            catch (Exception)
            { }
        }

        public Menu this[HRISEnums.MenuItems item]
        {
            get
            {
                if (this.SubMenus.Any(i => i.MenuItem == item))
                {
                    var menu = (Menu)this.SubMenus.First(menuItem => menuItem.MenuItem == item);
                    if (menu != null)
                    {
                        menu.ConfigureMenu();
                    }

                    return menu;
                }

                throw new Exception("Menu not defined or doesn't exists on this level!");
            }
        }
    }
}
